/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Web;

import Control.printers;
import DA.*;
import Entity.*;
import javax.servlet.RequestDispatcher;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author theInterloper
 */
@WebServlet(name = "shopControl", urlPatterns = {"/craftShop2/shopControl"})
public class shopControl extends HttpServlet {
    
    
    
    
    

    private static Artist readArtistFromSession(HttpServletRequest request) {
        Artist artist = new Artist();
        HttpSession session = request.getSession();
        //session.setAttribute("artistInfo", artist);
        artist = (Artist) session.getAttribute("artistInfo");
        if(artist!= null){
            Control.printers.printArtist(artist);
        } 
        return artist;
    }

    private static Customer readCustomerFromSession(HttpServletRequest request) {
        Customer customer = new Customer();
        HttpSession session = request.getSession();
        //session.setAttribute("artistInfo", artist);
        customer = (Customer) session.getAttribute("customerInfo");
        if(customer!= null){
            Control.printers.printCustomer(customer);
        }
        return customer;
       
    }

    public static void loadAllArtistsToSession(HttpServletRequest request, HttpServletResponse response) throws SQLException {           
        System.out.println("trip artist");
        HttpSession session = request.getSession();
         if(session.getAttribute("artistcollection")== null){
            System.out.println("no artist data found loading data");
            Collection artistCollection = new ArrayList<Artist>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("artist");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Artist artist = new Artist();
                artist = artistDA.read (i);
                artistCollection.add(artist);
                System.out.println((max - i) + " artists remaining to read");
            }
            //HttpSession session = request.getSession();
            session.setAttribute("artistcollection", artistCollection);
        }
         System.out.println(" artist data found, no loading necessary ");
    }

    public static void loadAllItemsToSession(HttpServletRequest request, HttpServletResponse response) throws SQLException { 
        System.out.println("trip item");
        HttpSession session = request.getSession();
        if(session.getAttribute("itemcollection")== null){
            System.out.println("no item data found loading data");
            Collection itemCollection = new ArrayList<Item>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("item");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Item item = new Item();
                item = itemDA.read (i);
                itemCollection.add(item);
                System.out.println((max - i) + " items remaining to read");
            }
            session.setAttribute("itemcollection", itemCollection);    
        }
        System.out.println(" item data found, no loading necessary ");
        
    }

    public static void loadAllCustomersToSession(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        System.out.println("trip customer");
        HttpSession session = request.getSession();
        if(session.getAttribute("customercollection")== null){
            System.out.println("no customer data found loading data");
            Collection customerCollection = new ArrayList<Customer>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("customer");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Customer customer = new Customer();
                customer = customerDA.read (i);
                customerCollection.add(customer);
                System.out.println((max - i) + " customers remaining to read");
            }
            session.setAttribute("customercollection", customerCollection);    
        }
        System.out.println(" customer data found, no loading necessary ");
        
    }
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //<editor-fold defaultstate="collapsed" desc="login check">
        String userName = request.getParameter("log");
        String passWord = request.getParameter("pwd");
        int loginControl = common.artistLoginContoller(userName, passWord);
        if(loginControl == 3){
            loginControl = common.customerLoginController(userName, passWord);     
        }
        loginTester(loginControl);
        
        if(loginControl == 1){
            Artist artist = new Artist();
            artist = artistDA.readByUserName(userName);
            //cookieControl.writeArtistCookie(response,a1);
            
            writeArtistToSession(artist, request);
            boolean isLoggedIn = true;
            HttpSession session = request.getSession();
            session.setAttribute("artistisloggedin", new Boolean(isLoggedIn));
            testSession(request);
        }
        if(loginControl == 4){
            Customer customer = new Customer();
            customer = customerDA.readByUserName(userName);
            System.out.println("**********************The customer returned after validation is:");
            printers.printCustomer(customer);
            System.out.println("****************************************************************");
            writeCustomerToSession(customer, request);
            boolean isLoggedIn = true;
            HttpSession session = request.getSession();
            session.setAttribute("customerisloggedin", new Boolean(isLoggedIn));
            testSession(request);
        }
        
  
        System.out.println("The username entered is: " + userName);
        System.out.println("The password entered is: " + passWord);
        System.out.println("The validator returned a value of:" + loginControl);
        
        //</editor-fold>
        
        String destination = "/main.jsp";
        RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
	rd.forward(request, response);
        
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet shopControl</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet shopControl at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(shopControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(shopControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void loginTester(int loginControl) {
        if(loginControl == 1){
            System.out.println("User = Artist. Username: True. Password: True");    
        }
        if(loginControl == 2){
            System.out.println("User = Artist. Username: True. Password: False");
        }
        if(loginControl == 3){
            System.out.println("User != Artist. Username: False. Password: False");
        }
        if(loginControl == 4){
            System.out.println("User = Customer. Username: True. Password: True");
        }
        if(loginControl == 5){
            System.out.println("User = Customer. Username: True. Password: False");    
        }
        if(loginControl == 6){
            System.out.println("User != Customer or Artist. Username: False. Password: False");
        }
    }

    private void writeArtistToSession(Artist artist, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("artistInfo", artist);
    }

    private void writeCustomerToSession(Customer customer, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("customerInfo", customer);
    }

    private void testSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Boolean isLoggedIn;
        isLoggedIn = (Boolean)session.getAttribute("isloggedin");
        System.out.println("The value of the retirved boolean is " + isLoggedIn);
    }
}
